package com.zhuangjie.wx.helper;


import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.WxMaSubscribeService;
import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
import com.zhuangjie.wx.entity.WechatSubscriptionMessage;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.stream.Collectors;

/**
 * wx订阅消息助手
 *
 * @author zhuangjie
 * @date 2023/12/10
 */
public class WxSubscribeMessageHelper {
    @Autowired
    private WxMaService wxMaService;
    public void send(WechatSubscriptionMessage wechatSubscriptionMessage) throws WxErrorException {
        // 发送微信订阅消息
        WxMaSubscribeService subscribeService = wxMaService.getSubscribeService();
        WxMaSubscribeMessage wxMaSubscribeMessage = new WxMaSubscribeMessage();
        wxMaSubscribeMessage.setTemplateId(wechatSubscriptionMessage.getTemplateId());
        wxMaSubscribeMessage.setToUser(wechatSubscriptionMessage.getOpenId());
        wxMaSubscribeMessage.setPage(wechatSubscriptionMessage.getMiniProgramPage());
        if (wechatSubscriptionMessage.getParams() != null) {
            List<WxMaSubscribeMessage.MsgData> messageParams = wechatSubscriptionMessage.getParams().entrySet().stream().map(entry -> new WxMaSubscribeMessage.MsgData(entry.getKey(), entry.getValue())).collect(Collectors.toList());
            wxMaSubscribeMessage.setData(messageParams );
        }
        subscribeService.sendSubscribeMsg(wxMaSubscribeMessage);
    }
}
